import axios from "axios";
import hmacSHA512 from "crypto-js/hmac-md5";
import dayjs from "dayjs";

const userId_key = "_UserId";
const platformId_key = "_PlatformId";

function hmacMD5(key, data) {
  return hmacSHA512(data, key).toString();
}

const today = dayjs().format("YYYY-MM-DD");

const auth = hmacMD5("baihua@2024", today);

const localUserId = sessionStorage.getItem(userId_key);
const localPlatformId = sessionStorage.getItem(platformId_key);

if (!localUserId) {
  sessionStorage.setItem(userId_key, "123");
}

if (!localPlatformId) {
  sessionStorage.setItem(platformId_key, "pc");
}

let _user_id = sessionStorage.getItem(userId_key);
let _phone_number = "";
let _platform_id = sessionStorage.getItem(platformId_key);

export const Authorization = `${today}:${auth}`;

console.log("Authorization", Authorization);

export function getUserId() {
  return _user_id;
}

export function getPlatformId() {
  return _platform_id;
}

export function getPhoneNumber() {
  return _phone_number;
}

export function setUserId(userId) {
  _user_id = userId;
  sessionStorage.setItem(userId_key, userId);
}

export function setPhoneNumber(phone_number) {
  _phone_number = phone_number;
}

export function setPlatformId(platformId) {
  _platform_id = platformId;
  sessionStorage.setItem(platformId_key, platformId);
}

const request = axios.create({
  baseURL: "/node-api",
  headers: {
    Accept: "application/json",
    Authorization: "Bearer " + Authorization,
    "Content-Type": "application/json",
  },
});

request.interceptors.response.use(
  (res) => {
    return res;
  },
  (err) => {
    if (err.response.status === 401) {
      import("@/store").then((module) => {
        module.useAppStore.setState({ logined: false });
      });
    }
  }
);

export interface IResultItem {
  question: string;
}

export interface IResult {
  data?: any;
  results: IResultItem[];
}

export interface IRequestParams {
  /**
   * 用户id
   */
  user_id?: string;

  /**
   * "问题类型" 'qa' 'law' 'case'
   */
  question_type: "qa" | "law" | "case";
}

/**
 * pc-换一批问题接口、示例的接口【9、1】
 * @param p
 * @returns
 */
export function fetchRecommendQuestion(p?: IRequestParams): Promise<IResult> {
  // return import("@/mock/recommend_question.json").then((res) => {
  //   return res.default;
  // });
  return request({
    method: "POST",
    url: "/recommend_question",
    data: {
      user_id: getUserId(),
      question_type: p.question_type,
    },
  }).then((res) => {
    return res.data;
  });
}

/**
 * 法律检索【10】
 * 
 * 请求参数：
{
  "keyword"：'关键字'
  "category":'效力级别'：法律、司法解释、行政法规、地方性法规...
  "platform":'发行机关'：全国代表大会、国务院、上海人力资源社会保障厅、北京人力资源社会保障厅...
  "publish_date":'发行年份'：全国代表大会、国务院、上海人力资源社会保障厅、北京人力资源社会保障厅...
  "basic_implementYear":'实施年份':'暂时无这个数据'
  "basic_implementliness":'实效'：'默认都是生效',
  "page_size":'10';'每页展示'
  "current_page":current_page;'当前页数'
}
 * @param p 
 * @returns 
 */
export function fetchKgSearchLaw(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/kg_search_law",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 案例检索【10】
 * 
请求参数：
    20241220 高级检索：支持 关键字、法院、裁判年份、审判程序
{
  "keyword"：'关键字'
  "court":'地域与法院'：
  "judgment_date":'裁判年份'
  "case_status":'裁判程序'：
  "page_size":'10';'每页展示'
  "current_page":current_page;'当前页数'
}
 * @param p 
 * @returns 
 */
export function fetchKgSearchCase(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/kg_search_case",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 法律详情【10】
 *
 * @param p
 * @returns
 */
export function fetchKgLawDetail(id: string): Promise<IResult> {
  return request({
    method: "get",
    url: "/kg_law_detail/" + id,
  });
}

/**
 * 案例详情【13】【14】
 *
 * @param p
 * @returns
 */
export function fetchKgCaseDetail(id: string): Promise<IResult> {
  return request({
    method: "get",
    url: "/kg_case_detail/" + id,
  });
}

/**
 * 文本阅读图片上传接口 【17】
 * 
 请求参数：
{
  "user_id":"用户id"，string 必须 
  "file_type":"文件类型"，string 必须 
  "user_id":"用户id"，string 必须 
}
 */
export function fetchUploadFile(
  p: FormData,
  onUploadProgress: any
): Promise<IResult> {
  p.append("user_id", getUserId());

  return request({
    method: "POST",
    url: "/upload_file",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress,
    data: p,
  });
}

/**
 * 服务名称：创建聊天 【done】【pc、小程序】【3】；对话创建时，需要调用这个接口
 * 
 请求参数：
    {
       "user_id": user_id: getUserId(), # 用户ID     
       "user_name": user_name,  # 用户名     
       "sender": # 创建着 机器人回答"robot" 用户是"user"
       "message":"消息内容"
       "type":消息类型['QA'、'Law'、 'Case'、 'wenshu']
    }
 */
export function fetchCreateChat(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/create_chat",
    data: {
      user_id: getUserId(),
      platform_id: getPlatformId(),
      ...p,
    },
  });
}

/**
 * 对话更新;数据生成结束，需要调用一次这个接口
 * @param p
 * @returns
 */
export function fetchUpdateChat(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/add_child_chat",
    data: {
      user_id: getUserId(),
      sender: "robot",
      ...p,
    },
  });
}

/**
 * 获取聊天信息
 */
export function fetchGetChatInfo(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/get_chat_info",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 生成文书
 */
export function fetchGeneratorText(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/generated_text",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 获取文书内容
 */
export function fetchGetGeneratorText(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/get_wenshu_content",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 保存文书
 */
export function fetchSaveGetGeneratorText(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/save_wenshu_content",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 更新文书
 */
export function fetchUpdateGetGeneratorText(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/update_wenshu_content",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 下载文书
 */
export function fetchDownloadGetGeneratorText(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/convert_markdown_to_word",
    data: {
      user_id: getUserId(),
      ...p,
    },
  });
}

/**
 * 历史对话-收藏功能\置顶\删除\重命名功能
 */
export function fetchUpdateChatHistory(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/update_chat_history",
    data: {
      chat_id: p.chat_id,
      title: p.title,
      is_favorite: p.isFavorite,
      is_pinned: p.isPinned,
      is_deleted: p.isDeleted,
    },
  });
}

/**
 * 历史对话-点赞 点踩功能
 */
export function fetchUpdateFeedback(p?: any): Promise<IResult> {
  return request({
    method: "POST",
    url: "/update_feedback",
    data: {
      chat_id: p.chat_id,
      child_chat_id: p.child_chat_id,
      like: p.like,
      dislike: p.dislike,
      dislike_content: p.dislike_content,
    },
  });
}

/**
 * 校验token
 */
export function fetchValidateTOken(token: string): Promise<IResult> {
  return request({
    method: "POST",
    url: "/validate_token",
    data: {
      token: token,
    },
  });
}

/**
 * 删除消息
 */
export function fetchDeleteMessage(child_chat_id: string): Promise<IResult> {
  return request({
    method: "POST",
    url: "/delete_child_message",
    data: {
      child_chat_id: child_chat_id,
    },
  });
}

/**
 * 发送验证码
 */
export function fetchSendCode(phone_number: string): Promise<IResult> {
  return request({
    method: "POST",
    url: "/send_verification_code",
    data: {
      phone_number,
    },
  });
}

/**
 * 登录
 */
export function fetchLogin(p: any): Promise<any> {
  return request({
    method: "POST",
    url: "/login",
    data: {
      phone_number: p?.phone_number,
      verification_code: p?.verification_code,
    },
  });
}

/**
 * 获取用户信息接口
 */
export function fetchGetUserInfo(): Promise<any> {
  return request({
    method: "POST",
    url: "/get_user_info",
  });
}

/**
 * 退出
 */
export function fetchLogout(): Promise<any> {
  return request({
    method: "POST",
    url: "/logout",
  });
}
